<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<title>Explained: What are Node.js modules? - The Node Beginner Blog</title>

<meta property="og:site_name" content="The Node Beginner Blog">
<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="fb:profile_id" content="1144782312">
<meta property="fb:app_id" content="150404395523663">
<meta property="article:author" content="https://www.facebook.com/NodeBeginner/">
<meta property="article:tag" content="Node.js">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="Programming">
<meta property="article:tag" content="Software">
<meta property="article:tag" content="Tutorial">
<meta property="fb:pages" content="319963981788483">
<meta property="og:url" content="https://www.nodebeginner.org/blog/post/nodejs-tutorial-what-are-node.js-modules/">
<meta property="og:title" content="Explained: What are Node.js modules?">
<meta property="og:image" content='https://www.nodebeginner.org/blog/images/nodejs-tutorial-what-are-node.js-modules.png'>
<meta property="og:image:secure_url" content='https://www.nodebeginner.org/blog/images/nodejs-tutorial-what-are-node.js-modules.png'>
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:description" content='It&#39;s easy to create a mess in your code if you don&#39;t use Node.js modules. This tutorial explains everything you need to know for a cleanly structured codebase.'>


<link rel="stylesheet" href="https://www.nodebeginner.org/blog/css/slim.css">
<link rel="stylesheet" href="https://www.nodebeginner.org/blog/css/highlight.min.css">


<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/apple-touch-icon-144-precomposed.png">
<link rel="shortcut icon" href="/favicon.ico">


<link href="" rel="alternate" type="application/rss+xml" title="The Node Beginner Blog" />

</head>

<body>
  <div class="container">
    <div class="header">
  <h1 class="site-title"><a href="https://www.nodebeginner.org/blog/">The Node Beginner Blog</a></h1>
  <p class="site-tagline">Your regularly updated tutorial resource for all things Node.js.</p>

  
</div>
    <div class="content">
      <div class="posts">
        <div class="post">
          <h2 class="post-title"><a href="https://www.nodebeginner.org/blog/post/nodejs-tutorial-what-are-node.js-modules/">Explained: What are Node.js modules?</a></h2>
          <span class="post-date">Jul 5, 2017 </span>
          <div class="post-content">
            <p>When you write Node.js applications, you could actually put all your code into one huge <em>index.js</em> file, no matter
how large or complex your application is. The Node.js interpreter doesn&rsquo;t care. But in terms of code organization,
you would end up with a hard to understand and hard to debug mess quite quickly. So as a human being, you should care
about how to structure your code. This is where modules come in. </p>

<p>You can think of Node.js modules as JavaScript libraries - a certain part of your overall codebase (for example, a
collection of functions) which you want to keep together, but which you also want to keep separated from the rest of
your codebase to keep things cleanly separated.</p>

<p>Just like we keep our socks in one drawer and our shirts in another drawer in our wardrobe - even if we combine
both to create an outfit for the day - we can keep different parts of our codebase in different modules and then combine
them into a coherent application.</p>

<h2 id="built-in-modules">Built-in Modules</h2>

<p>Even if we don&rsquo;t create any Node.js modules ourselves, we already have modules at our disposal because the Node.js
environment provides built-in modules for us. We already encountered one of these modules in this blog when we looked at
<a href="/blog/post/nodejs-tutorial-whatwg-url-parser/">how to use the built-in WHATWG URL parser</a>.</p>

<p>Within our own code file, we needed to use existing code which was declared elsewhere - in this case, the <code>URL</code> class
which is part of the built-in Node.js module <code>url</code>:</p>

<pre><code>var URL = require('url').URL;
</code></pre>

<p>The <code>require('url')</code> part is what gives us access to the code of the <code>url</code> module. Where and how this module is defined
is completely opaque for us - all we need to know is its name - <code>url</code> - and the attributes it exposes, like <code>URL</code>.</p>

<p>Other built-in modules directly expose the attribute we need (which often are JavaScript objects). The <code>http</code> module is
an example:</p>

<pre><code>var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('Hello World!');
}).listen(8080);
</code></pre>

<p>Here, requiring the <code>http</code> module gives us direct access to an <code>http</code> object, whose methods, like <code>createServer</code>, we can
then use.</p>

<p><strong>The Node Beginner Book</strong> explains <a href="https://www.nodebeginner.org/">how to write a complete web server with Node.js</a>
using the built-in <code>http</code> module.</p>

<h2 id="external-modules">External Modules</h2>

<p>The built-in modules which ship with Node.js allow to solve a lot of coding problems without reinventing the wheel for
every new application, but what really boosts Node.js programming productivity is the huge ecosystem of open source
modules provided by the Node.js community. These modules can be integrated into our codebase, too, but because they are
not built-in and don&rsquo;t ship directly with each installation of Node.js, it is not enough to <code>require</code> them from our own
code. We need to install the codebase containing the external module locally first, which is made very easy thanks to
<em>NPM</em>, the Node Package Manager.</p>

<p>See this blog post which describes
<a href="/blog/post/nodejs-tutorial-optimizing-code-performance-using-async/">how to use the <em>async</em> library</a> for an
example of how to use external modules.</p>

<p>Also, <strong>The Node Craftsman Book</strong> has a chapter on the details of
<a href="https://leanpub.com/b/node-beginner-and-craftsman-bundle">working with NPM</a>.</p>

<h2 id="creating-your-own-modules">Creating your own modules</h2>

<p>Built-in and external modules are provided by others, but nothing stops you from creating your own Node.js modules.</p>

<p>The following example creates a module <code>myRandom</code> which provides a helper function that returns random number between 1
and 10:</p>

<p>File <code>myRandom.js</code>:</p>

<pre><code>function getRandom(min, max) {
      return Math.random() * (max - min) + min;
}

exports.between1and10 = function() {
      return getRandom(1, 10);
};
</code></pre>

<p>You would put this code into it&rsquo;s own file called <code>myRandom.js</code>. Because this file exists and provides attributes to the
outer world via <code>exports</code>, another file <code>index.js</code> can use the exported functionality:</p>

<p>File <code>index.js</code>:</p>

<pre><code>var myRandom = require('./myRandom.js');

console.log(myRandom.between1and10());
</code></pre>

<p>Again, <code>require</code> comes into play, making the exported attributes of the local <code>myRandom</code> module available - in this
case, the <code>between1and10</code> function.</p>

<p>Note: While the module system allows to <em>expose</em> functionality of a module, it also allows to <em>hide</em> functionality which
is not needed outside of the module, simply by not exporting the functionality via <code>exports</code>. Even though the <code>index.js</code>
file has required the <code>myRandom.js</code> file, it cannot access its non-exported <code>getRandom</code> function:</p>

<pre><code>var myRandom = require('./myRandom.js');

console.log(myRandom.getRandom(5, 99));
</code></pre>

<p>will result in a <code>TypeError: myRandom.getRandom is not a function</code>.</p>

<p>By hiding implementation details in a module and only exposing those parts which are to be used by other parts of your
codebase, you can keep your codebase well organized.</p>

<hr />

<p>Learn more about working with modules and <a href="https://www.nodebeginner.org/#a-basic-http-server">building your own web server</a>
application with Node.js with <strong>The Node Beginner Book</strong> - the first part of this
<a href="https://www.nodebeginner.org/">step-by-step Node.js tutorial</a> is available for free!</p>
          </div>
        </div>
        <div class="pagination">
          
            <a class="btn next " href="https://www.nodebeginner.org/blog/post/nodejs-tutorial-how-to-work-with-websockets/">Next</a>
          
          
            <a class="btn previous " href="https://www.nodebeginner.org/blog/post/nodejs-tutorial-optimizing-code-performance-using-async/">Prev</a>
          
        </div>
      </div>
    </div>
    
    <div class="footer">
  
  <p>Copyright (c) 2017 Manuel Kiessling</p>
  
</div>

  </div>
  <script src="https://www.nodebeginner.org/blog/js/slim.js"></script>
  <script src="https://www.nodebeginner.org/blog/js/highlight.min.js"></script>
  <script>
    hljs.initHighlightingOnLoad();
  </script>

</body>

</html>
